import { RequestOptions } from "../types/commonType";

const baseUrl: string = "http://127.0.0.1:3747";



export class NetworkError extends Error {
    constructor(message: string, public status: number) {
        super(message);
        this.name = "NetworkError";
    }
}

export async function networkRequest<T>(url: string, options: RequestOptions): Promise<T> {
    const fullUrl: string = buildUrl(baseUrl + url, options.params);

    try {
        // 如果是 GET 或 HEAD 请求，确保不包含 body
        if (options.method === "GET" || options.method === "HEAD") {
            delete options.body;
        }

        const response = await fetch(fullUrl, options);

        if (!response.ok) {
            // Assuming the server returns JSON error data
            const errorData = await response.json();
            throw new NetworkError(errorData.message || "Request failed", response.status);
        }

        // Assuming the server returns JSON data
        const data: T = await response.json();
        return data;
    } catch (error) {
        // 如果是 NetworkError，则直接抛出
        if (error instanceof NetworkError) {
            throw error;
        }

        // 否则，抛出一个通用的错误
        console.error("Request error:", error);
        throw new Error("An unexpected error occurred.");
    }
}


function buildUrl(url: string, params?: Record<string, any>): string {
    if (!params) {
        return url;
    }

    const queryString = Object.keys(params)
        .map(key => encodeURIComponent(key) + "=" + encodeURIComponent(params[key]))
        .join("&");

    return url + (url.includes("?") ? "&" : "?") + queryString;
}
